<script setup lang="ts">
import {nextTick, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {getFirstParty, saveFirstParty, updateFirstParty} from '@/api/firstParty'
import {FirstPartyC} from '@/types/firstPartyC'

const visible = ref(false)
const dataFormRef = ref()
const dataForm = ref<FirstParty>(new FirstPartyC())

const dataRule = ref({
  firstPartyName: [{
    required: true,
    message: '甲方（用人单位）名称不能为空',
    trigger: 'blur',
  }],
  address: [{
    required: true,
    message: '地址不能为空',
    trigger: 'blur',
  }],
  legalPerson: [{
    required: true,
    message: '法定代表人（或者主要负责人）不能为空',
    trigger: 'blur',
  }],
})

function init(id: number) {
  visible.value = true
  nextTick(async () => {
    if (id) {
      dataForm.value = await getFirstParty(id)
    } else {
      dataFormRef.value.resetFields()
    }
  })
}

const emits = defineEmits(['refreshDataList'])

// 表单提交
async function dataFormSubmit() {
  console.log('save firstParty: ', dataForm.value)
  if (dataForm.value.id) {
    await updateFirstParty(dataForm.value)
  } else {
    await saveFirstParty(dataForm.value)
  }
  visible.value = false
  emits('refreshDataList')
  ElMessage({
    type: 'success',
    message: '操作成功',
    duration: 1000,
  })
}

defineExpose({
  init,
})
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="160px"
      @keyup.enter="dataFormSubmit()"
    >
      <el-form-item label="甲方名称" prop="firstPartyName">
        <el-input
          v-model="dataForm.firstPartyName"
          placeholder="甲方名称"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="地址"/>
      </el-form-item>
      <el-form-item label="法定代表人" prop="legalPerson">
        <el-input
          v-model="dataForm.legalPerson"
          placeholder="法定代表人"
        />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
